const express = require('express')
const router = express.Router()
const User = require('./../models/user')
require('./../util/dateFormate')
const { idGenerator } = require('./../util/idGenerator')

/** 用户登录管理：登录 */
router.post('/login', (req, res, next) => {
  // 读取用户输入的用户名和密码
  const param = {
    userName: req.body.userName,
    userPwd: req.body.userPwd
  }
  // 在数据库内查询校验
  User.findOne(param, (err, user) => {
    if (err) {
      res.json({
        status: '1',
        msg: '数据库查找出错：' + err.message
      })
    } else {
      // user 不为空，说明该账户存在
      if (user) {
        // 将该用户 id 和用户名写入 cookie
        res.cookie('userId', user.userId, { maxAge: 1000 * 60 * 60 * 24 })
        res.cookie('userName', user.userName, { maxAge: 1000 * 60 * 60 * 24 })
        res.json({
          status: '0',
          msg: '成功，合法账户'
        })
      } else {
        res.json({
          status: '1',
          msg: '失败，没有找到该账户'
        })
      }
    }
  })
})
/** 用户登录管理：登出 */
router.post('/logout', (req, res, next) => {
  res.clearCookie('userId')
  res.clearCookie('userName')
  res.json({
    status: '0',
    msg: '',
    result: ''
  })
})
/** 用户登录管理：校验是否登录 */
router.get('/checkLogin', (req, res, next) => {
  if (req.cookies['userId']) {
    res.json({
      status: '0',
      msg: 'pass login check',
      result: { userName: req.cookies['userName'] }
    })
  }
})

/** 购物车管理：获取商品列表 */
router.get('/cart/cartList', (req, res, next) => {
  const userId = req.cookies['userId']
  User.findOne(
    { userId },
    (err, result) => {
      if (err) {
        res.json({
          status: '1',
          msg: err.message,
          result: ''
        })
      } else {
        res.json({
          status: '0',
          msg: 'get cart list succ',
          result: {
            list: result.cartList
          }
        })
      }
    }
  )
})

/** 购物车管理：删除商品 */
router.post('/cart/removeItem', (req, res, next) => {
  const userId = req.cookies['userId']
  const productId = req.body['productId']
  User.updateOne(
    { userId },
    { $pull: { cartList: { productId: productId } } },
    (err, result) => {
      if (err) {
        res.json({
          status: '1',
          msg: err.message,
          result: ''
        })
      } else {
        res.json({
          status: '0',
          msg: 'remove item succ',
          result: result
        })
      }
    }
  )
})

/** 购物车管理：修改商品数量 */
router.post('/cart/alterItemNum', (req, res, next) => {
  const userId = req.cookies['userId']
  const productId = req.body['productId']
  const productNum = req.body['productNum']
  User.updateOne(
    { userId, 'cartList.productId': productId },
    { $set: { 'cartList.$.productNum': productNum } },
    (err, result) => {
      if (err) {
        res.json({
          status: '1',
          msg: err.message,
          result: ''
        })
      } else {
        res.json({
          status: '0',
          msg: '',
          result: result
        })
      }
    }
  )
})

/** 购物车管理：切换单个商品的选中状态 */
router.post('/cart/toggleItemCheck', (req, res, next) => {
  const userId = req.cookies['userId']
  const productId = req.body['productId']
  const checked = req.body['checked']
  User.updateOne(
    { userId, 'cartList.productId': productId },
    { $set: { 'cartList.$.checked': checked } },
    (err, result) => {
      if (err) {
        res.json({
          status: '1',
          msg: err.message,
          result: ''
        })
      } else {
        res.json({
          status: '0',
          msg: 'toggle item check succ',
          result: result
        })
      }
    }
  )
})

/** 购物车管理：切换商品全选或者全不选状态 */
router.post('/cart/toggleAllCheck', (req, res, next) => {
  const userId = req.cookies['userId']
  const flag = req.body['flag'] ? '1' : '0' // 全选或者全不选的标志位
  User.findOne({ userId })
    .then(user => {
      user.cartList.forEach(item => {
        item.checked = flag
      })
      user.save()
        .then(result => {
          res.json({
            status: '0',
            msg: 'toggle all item check succ',
            result: result
          })
        })
        .catch(err => {
          res.json({
            status: '1',
            msg: err.message,
            result: ''
          })
        })
    })
    .catch(err => {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    })
})

/** 地址管理：获取用户收货地址信息列表 */
router.get('/address/list', (req, res, next) => {
  const userId = req.cookies['userId']
  User.findOne({ userId })
    .then(user => {
      res.json({
        status: '0',
        msg: 'get address list succ',
        result: user.addressList
      })
    })
    .catch(err => {
      res.json({
        status: '0',
        msg: err.message,
        result: ''
      })
    })
})

/** 地址管理：设置用户的默认收货地址 */
router.post('/address/setDefault', (req, res, next) => {
  const userId = req.cookies['userId']
  const addressId = req.body['addressId']
  // res.send(`userId: ${userId}, addressId: ${addressId}`)
  User.findOne({ userId })
    .then(user => {
      // 操作数据库，设置默认地址
      user.addressList.forEach(item => {
        item.isDefault = item.addressId === addressId
      })
      user.save()
        .then(result => {
          res.json({
            status: '0',
            msg: 'set default succ',
            result: result
          })
        })
        .catch(err => {
          res.json({
            status: '1',
            msg: err.message,
            result: ''
          })
        })
    })
    .catch(err => {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    })
})

/** 地址管理：移除一个收货地址 */
router.post('/address/remove', (req, res, next) => {
  const userId = req.cookies['userId']
  const addressId = req.body['addressId']
  User.findOne({ userId })
    .then(user => {
      user.addressList = user.addressList.filter(item => item.addressId !== addressId)
      user.save()
        .then(result => {
          res.json({
            status: '0',
            msg: 'remove address succ',
            result: result
          })
        })
        .catch(err => {
          res.json({
            status: '1',
            msg: err.message,
            result: ''
          })
        })
    })
    .catch(err => {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    })
})

/** 订单管理：生成一个新的订单 */
router.post('/order/create', (req, res, next) => {
  const userId = req.cookies['userId']
  const addressId = req.body['addressId']
  const orderTotal = req.body['orderTotal']
  User.findOne({ userId })
    .then(user => {
      if (!user) {
        res.json({
          status: '1',
          msg: `Not found userId: ${ userId }`,
          result: user
        })
        return
      }
      // 调试使用：清除订单，待删除
      // user.orderList = []
      // 根据 addressId 找到对应的 address
      const addressInfo = user.addressList.find(item => item.addressId === addressId)
      // 校验订单总金额
      // todo
      // 获取用户确定购买的商品列表
      const goodsList = user.cartList.filter(item => item.checked === '1')
      // 生成订单的 id
      const orderId = idGenerator('622')
      // 订单的状态 '1'为异常， '0'为正常
      const orderStatus = '0'
      // 创建订单的时间
      const createDate = new Date().Format('yyyy-MM-dd hh:mm:ss')
      // 创建一个订单对象
      const orderInfo = {
        orderId,
        orderStatus,
        orderTotal, // 正常来说，需要在数据库做检验
        goodsList,
        addressInfo,
        createDate
      }
      // 保存在用户的订单列表内
      user.orderList.push(orderInfo)
      // 在用户的购物车内删除已购买的商品
      user.cartList = user.cartList.filter(item => item.checked === '0')
      // 在数据库端保存
      user.save()
        .then(result => {
          res.json({
            status: '0',
            msg: '提交订单成功',
            result: { orderInfo }
          })
        })
        .catch(err => {
          res.json({
            status: '1',
            msg: err.message,
            result: ''
          })
        })
    }).catch(err => {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    })
})

/** 获取用户的历史订单 */
router.get('/order/list', (req, res, next) => {
  const userId = req.cookies['userId']
  User.findOne({ userId })
    .then(user => {
      if (!user) {
        res.json({
          status: '1',
          msg: `Not found userId: ${userId}`,
          result: ''
        })
        return
      }
      res.json({
        status: '0',
        msg: '获取历史订单列表成功',
        result: user.orderList
      })
    })
    .catch(err => {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    })
})

module.exports = router
